<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use think\Db;
use think\Loader;

class Level extends Base
{
    /**
     * 等级列表
     * @return mixed
     */
    public function LevelList(){
        //总记录条数
        $Count = Db::name('user_level')->count();
        $this->assign('Count',$Count);

        //等级列表
        $LevelList = Db::name('user_level')->select();
        foreach($LevelList as $k=>$v){
            //下属会员人数
            $LevelList[$k]['count_user'] = Db::name('user')->where(['level'=>$LevelList[$k]['id']])->count();
        }
        $this->assign('LevelList',$LevelList);

        return $this->fetch('LevelList');
    }

    /**
     * 添加等级
     * @return mixed
     */
    public function LevelAdd(){
        //Post请求操作
        if(IsPost()){
            //请求数据
            $Data = Param();

            //查看级别是否存在
            $LevelInfo = Db::name('user_level')->where(['name'=>$Data['name']])->find();
            if(!empty($LevelInfo)){
                return ['status'=>0,'message'=>'该级别已存在，请勿重复添加'];
            }

            $Data['rebate_2'] = $Data['rebate_2']/100;
            $Data['rebate_3'] = $Data['rebate_3']/100;
            $Data['rebate_4'] = $Data['rebate_4']/100;
            $Data['rebate_5'] = $Data['rebate_5']/100;
            if(Db::name('user_level')->insert($Data)){
                return ['status'=>1,'message'=>'添加成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
        return $this->fetch('LevelAdd');
    }

    /**
     * 等级编辑
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function LevelEdit(){
        $LevelInfo = Db::name('user_level')->where(['id'=>Param('id')])->find();
        //Post请求操作
        if(IsPost()){
            //请求数据
            $Data = Param();
            //修改表中数据
            if(Db::name('user_level')->update($Data) !== false){
                return ['status'=>1,'message'=>'修改成功'];
            }else{
                return ['status'=>0,'message'=>'无修改'];
            }
        }

        $this->assign('LevelInfo',$LevelInfo);
        return $this->fetch('LevelEdit');
    }

    /**
     * 等级删除
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function LevelDelete(){
        //Post请求操作
        if(IsPost()){
            //当前级别下属会员数量
            $CountUser = Db::name('user')->where(['level'=>Param('id')])->count();
            //判断当前级别是否下属会员
            if($CountUser > 0){
                return ['status'=>0,'message'=>'该级别下有用户，不能删除'];
            }else{
                //删除表中数据
                if(Db::name('user_level')->where(['id'=>Param('id')])->delete()){
                    return ['status'=>1,'message'=>'删除成功'];
                }else{
                    return ['status'=>0,'message'=>'系统错误，请重试'];
                }
            }

        }
    }

    /**
     * 等级申请列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function LevelApply()
    {
        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'status' => 5,
                'username' => '',
                'begin_time' => '',
                'end_time' => '',
            ];

        }

        $this->assign('Data',$Data);
        $Where = [];
        //等级查询
        if($Data['status'] != 5){
            $Where['status'] = $Data['status'];
        }

        //会员账号查询
        if($Data['username'] != ''){

            //根据会员账号找出会员ID
            $UserInfo = UserInfo(['username'=>$Data['username']]);
            $Where['user_id'] = $UserInfo['id'];

        }

        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }


        //总记录条数
        $Count = LevelApplyCount($Where);
        $this->assign('Count', $Count);

        //申请信息
        $LevelApplyList = LevelApplyList($Where);

        //定存金额统计
        foreach($LevelApplyList['LevelApplyList'] as $k=>$v){
            $LevelApplyList['LevelApplyList'][$k]['deposit'] = Db::name('user_deposit')->where(['user_id'=>$LevelApplyList['LevelApplyList'][$k]['user_id']])->sum('surplus_num');;
        }
        $this->assign('LevelApplyList', $LevelApplyList['LevelApplyList']);

        //分页
        $this->assign('Page', $LevelApplyList['Page']);

        //级别信息
        $LevelList = LevelList();
        $this->assign('LevelList', $LevelList);

        return $this->fetch('LevelApply');
    }

    /**
     * 等级申请导出
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function LevelApplyExport(){

        //条件查询
        $Data = Param();
        if (empty($Data)){
            $Data = [
                'status' => 5,
                'username' => '',
                'begin_time' => '',
                'end_time' => '',
            ];

        }

        $this->assign('Data',$Data);
        $Where = [];
        //等级查询
        if($Data['status'] != 5){
            $Where['status'] = $Data['status'];
        }

        //会员账号查询
        if($Data['username'] != ''){

            //根据会员账号找出会员ID
            $UserInfo = UserInfo(['username'=>$Data['username']]);
            $Where['user_id'] = $UserInfo['id'];

        }

        //时间查询
        if($Data['begin_time'] != '' && $Data['end_time'] == ''){   //只有开始时间没有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $Where['add_time'] = array('egt',$BeginTime );
        }

        if($Data['begin_time'] == '' && $Data['end_time'] != ''){   //只有结束时间没有开始时间
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array('elt',$EndTime );
        }

        if($Data['begin_time'] != '' && $Data['end_time'] != ''){   //有开始时间有结束时间
            $BeginTime = strtotime($Data['begin_time']);
            $EndTime = strtotime($Data['end_time']);
            $Where['add_time'] = array(array('egt',$BeginTime ),array('elt',$EndTime ));
        }

        $xlsData = Db('user_level_apply')->where($Where)->select();

        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.Worksheet.Drawing');
        Loader::import('PHPExcel.PHPExcel.Writer.Excel2007');
        $objExcel = new \PHPExcel();
        $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');

        $objActSheet = $objExcel->getActiveSheet();
        $key = ord("A");
        $letter =explode(',',"A,B,C,D,E,F,G,H");
        $arrHeader = array('会员账号','当前等级','理财金额','申请等级','申请时间','备注信息','处理时间','处理状态');

        //填充表头信息
        $lenth =  count($arrHeader);
        for($i = 0;$i < $lenth;$i++) {
            $objActSheet->setCellValue("$letter[$i]1","$arrHeader[$i]");
        };


        //填充表格信息
        foreach($xlsData as $k=>$v){
            //会员信息
            $UserInfo = UserInfo(['id'=>$xlsData[$k]['user_id']]);
            if(!empty($xlsData[$k]['status'])){
                $SureTime = date('Y-m-d H:i',$v['sure_time']);
            }else{
                $SureTime = '';
            }
            //当前等级信息
            $NowLevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
            //申请等级信息
            $ApplyLevelInfo = LevelInfo(['id'=>$xlsData[$k]['level_id']]);
            //处理状态
            if($xlsData[$k]['status'] == 0){
                $Status = '待处理';
            }elseif($xlsData[$k]['status'] == 1){
                $Status = '已通过';
            }elseif($xlsData[$k]['status'] == 2){
                $Status = '已驳回';
            }
            $k +=2;
            $objActSheet->setCellValue('A'.$k, $UserInfo['username']);
            $objActSheet->setCellValue('B'.$k, $NowLevelInfo['name']);
            $objActSheet->setCellValue('C'.$k, $UserInfo['balance_2']);
            $objActSheet->setCellValue('D'.$k, $ApplyLevelInfo['name']);
            $objActSheet->setCellValue('E'.$k, date('Y-m-d H:i',$v['add_time']));
            $objActSheet->setCellValue('F'.$k, $v['remarks']);
            $objActSheet->setCellValue('G'.$k, $SureTime);
            $objActSheet->setCellValue('H'.$k, $Status);
            // 表格高度
            $objActSheet->getRowDimension($k)->setRowHeight(20);

            $width = array(10,15,20,25,30);
            //设置表格的宽度
            $objActSheet->getColumnDimension('A')->setWidth($width[1]);
            $objActSheet->getColumnDimension('B')->setWidth($width[1]);
            $objActSheet->getColumnDimension('C')->setWidth($width[1]);
            $objActSheet->getColumnDimension('D')->setWidth($width[2]);
            $objActSheet->getColumnDimension('E')->setWidth($width[2]);
            $objActSheet->getColumnDimension('F')->setWidth($width[2]);
            $objActSheet->getColumnDimension('G')->setWidth($width[2]);
            $objActSheet->getColumnDimension('H')->setWidth($width[2]);
        }


        $outfile = "等级申请列表.xlsx";
        ob_end_clean();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$outfile.'"');
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");

        $objWriter->save('php://output');
    }

    /**
     * 等级申请通过
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function LevelSure(){
        //Post请求
        if(IsPost()){
            //请求数据
            $ID = Param('id');

            //申请信息
            $LevelApplyInfo = Db::name('user_level_apply')->where(['id'=>$ID])->find();
            $SaveData['status'] = 1;
            $SaveData['sure_time'] = time();
            $SaveData['save_level_id'] = Param('save_level_id');
            $SaveData['sure_remarks'] = Param('sure_remarks');
            $SaveData['is_tips'] = 1;

            if(Db::name('user_level_apply')->where(['id'=>$ID])->update($SaveData)){
                Db::name('user')->where(['id'=>$LevelApplyInfo['user_id']])->update(['level'=>$SaveData['save_level_id']]);
                return ['status'=>1,'message'=>'处理成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
    }

    /**
     * 升级申请驳回
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function LevelBack(){
        //Post请求
        if(IsPost()){
            //请求数据
            $ID = Param('id');

            $SaveData['status'] = 2;
            $SaveData['sure_time'] = time();
            if(Db::name('user_level_apply')->where(['id'=>$ID])->update($SaveData)){
                return ['status'=>1,'message'=>'驳回成功'];
            }else{
                return ['status'=>0,'message'=>'系统错误，请重试'];
            }
        }
    }

    /**
     * 等级申请记录修改
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function LevelApplyEdit(){
        $ID = Param('id');
        //等级列表
        $LevelList = LevelList();
        $this->assign('LevelList',$LevelList);

        //申请信息
        $ApplyInfo = Db::name('user_level_apply')->where(['id'=>$ID])->find();
        $ApplyInfo['username'] = UserInfo(['id'=>$ApplyInfo['user_id']])['username'];
        $ApplyInfo['deposit'] = Db::name('user_deposit')->where(['user_id'=>$ApplyInfo['user_id']])->sum('surplus_num');
        $this->assign('ApplyInfo',$ApplyInfo);

        return $this->fetch('LevelApplyEdit');
    }
}